/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 8/1/18
Time: 4:46 PM
 */

package com.ug_project.dict.engine.indextable

import java.nio.ByteBuffer

class IndexTableMeta(val table: IndexTable) {
    companion object {
        const val startPosition = 0
        const val metaSize = 16
    }

    private val channel = table.channel
    val bytes = ByteArray(metaSize)
    val buffer = ByteBuffer.wrap(bytes)

    var capacity = 0
    var used = 0
    var lastEmptyBlock = 0


    fun parse() {
        channel.position(startPosition.toLong())
        buffer.apply {
            clear()
            val readed = channel.read(buffer)
            if(readed == -1) return //تۇنجى قىتىم ئوقۇغاندا ھۆججەت مەۋجۇت بولمىسا ئوقىمىسىمۇ بولىدۇ
            flip()
            this@IndexTableMeta.capacity = int
            used = int
            lastEmptyBlock = int
        }
    }

    fun writeToChannel() {
        channel.position(startPosition.toLong())
        buffer.apply {
            clear()
            putInt(this@IndexTableMeta.capacity)
            putInt(used)
            putInt(lastEmptyBlock)
            flip()
            channel.write(buffer)
        }
    }

    init {
        parse()
    }
}